<?php

namespace model;

require_once __DIR__.'/../utils/MysqlDBUtils.php';

use utils\MysqlDBUtils;

class BorrowModel
{
    private $dbUtils;

    public function __construct()
    {
        $this->dbUtils = new MysqlDBUtils();
    }

    public function getPaginatedBorrow($q = '', $currentPage = 1, $perPage = 8)
    {
        $whereCondition='';
        if (!empty($q)){
            $qLike="%{$q}%";
            $whereCondition="WHERE br.id LIKE '$qLike' OR br.user_id LIKE '$qLike' OR br.book_id LIKE '$qLike'";
        }

        $totalSql="SELECT COUNT(*) AS total FROM borrow_record br {$whereCondition}";
        $totalResult=$this->dbUtils->prepareQuery($totalSql);
        $total=$totalResult?$totalResult[0]['total']:0;

        $offset=($currentPage-1)*$perPage;
        $sql = "SELECT * 
        FROM borrow_record br 
        LEFT JOIN bookprogram.book b ON b.id = br.book_id 
        LEFT JOIN bookprogram.user u ON u.id = br.user_id 
        {$whereCondition} 
        LIMIT $offset, $perPage";
        $borrows=$this->dbUtils->prepareQuery($sql);

        return[
            'borrows' => $borrows,
            'total' => $total,
            'currentPage' => $currentPage,
            'perPage' => $perPage,
            'totalPages' => max(1, ceil($total / $perPage))
        ];
    }

    // 添加借阅记录
    public function addBorrowRecord($userId, $bookId, $borrowTime)
    {
        $sql = "INSERT INTO borrow_record (user_id, book_id, borrow_time, status) VALUES (?, ?, ?, 0)";
        $params = [$userId, $bookId, $borrowTime];
        return $this->dbUtils->prepareExecute($sql, $params);
    }

    // 更新归还状态（传入借阅ID和归还时间）
    public function updateReturnStatus($borrowId, $returnTime,$status)
    {
        $sql = "UPDATE borrow_record SET return_time = ?, status = ? WHERE borrow_id = ?";
        $params = [$returnTime,$status, $borrowId];
        return $this->dbUtils->prepareExecute($sql, $params);
    }

    // 查询用户所有未归还的借阅记录
    public function getUnreturnedBorrows($userId)
    {
        $sql = "SELECT br.id, b.title, br.borrow_time 
                FROM borrow_record br 
                JOIN book b ON br.book_id = b.id 
                WHERE br.user_id = ? AND br.status = 1";
        $params = [$userId];
        return $this->dbUtils->prepareExecute($sql, $params);
    }

    // 查询用户所有借阅记录
    public function getAllBorrowsByUser($userId)
    {
        $sql = "SELECT br.id, b.title, br.borrow_time, br.return_time, 
                        CASE br.status WHEN 1 THEN '未归还' WHEN 2 THEN '已归还' END AS status
                FROM borrow_record br 
                JOIN book b ON br.book_id = b.id 
                WHERE br.user_id = ?";
        $params = [$userId];
        return $this->dbUtils->prepareExecute($sql, $params);
    }

    //删除用户
    public function deleteBorrow($id): array
    {
        $sql='DELETE FROM borrow_record WHERE borrow_id = ?';
        $params=[$id];
        return $this->dbUtils->prepareExecute($sql,$params);
    }
}